unit uThreadManager;

interface

uses
  Windows;

type
  TThreadManager = class
  public
    hThread: THandle;
    dwExitCode: DWORD;
    dwThreadID: DWORD;
    dwSuspend: DWORD;
    constructor Create; overload; virtual;
    constructor Create(lpStartAddress: Pointer; lpParameter: Pointer = nil; dwCreationFlags: DWORD = CREATE_SUSPENDED); overload; virtual;
    destructor Destroy; override;
    function IsActive(): Boolean;
    function Run(StartAddress: Pointer; Parameter: Pointer = nil): UInt64;
    function Suspend(): DWORD;
    function Resume(): DWORD;
    function Stop(): Boolean;
  private
    function InitThread(): Boolean;
  end;

var
  ThreadManager: TThreadManager;
  CS: TRTLCriticalSection;

implementation

function TThreadManager.InitThread(): Boolean;
begin
  Result := True;
end;

constructor TThreadManager.Create;
begin
  hThread := CreateThread(nil, 0, @TThreadManager.InitThread, nil, 0, dwThreadID);
end;

constructor TThreadManager.Create(lpStartAddress: Pointer; lpParameter: Pointer = nil; dwCreationFlags: DWORD = CREATE_SUSPENDED);
begin
  hThread := CreateThread(nil, 0, lpStartAddress, lpParameter, dwCreationFlags, dwThreadID);
end;

destructor TThreadManager.Destroy();
begin
  hThread := 0;
end;

function TThreadManager.IsActive(): Boolean;
begin
  Result := False;
  if GetExitCodeThread(hThread, dwExitCode) then
    Result := dwExitCode = STILL_ACTIVE;
end;

function TThreadManager.Run(StartAddress: Pointer; Parameter: Pointer = nil): UInt64;
begin
  Result := 0;
  if not IsActive then
  begin
    hThread := CreateThread(nil, 0, StartAddress, Parameter, 0, dwThreadID);
    Result := hThread;
  end;
end;

function TThreadManager.Suspend(): DWORD;
begin
  if IsActive then
    dwSuspend := SuspendThread(hThread);
  Result := dwSuspend;
end;

function TThreadManager.Resume(): DWORD;
begin
  if IsActive then
    dwSuspend := ResumeThread(hThread);
  Result := dwSuspend;
end;

function TThreadManager.Stop(): Boolean;
begin
  Result := False;
  if IsActive then
    Result := TerminateThread(hThread, 0);
end;

end.

